const morgan = require('morgan');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const express = require('express');
const app = express();

/**
 * 监控
 */
app.get('/watch', function (req, res) {
    return res.send({success: true});
});

let config = require('../config');
let utils = require('./utils');
let search = require('./utils/search')(config.elasticsearch);
let taobaoApi = require('./taobao')(config);
let modelsData = require('./models_data').newInstance(config.mysql_data);

let storage = {
    search: search,
    modelsData: modelsData,
    utils: utils,
    controller: utils.controller,
    config: config,
    paths: config.paths,
    taobaoApi: taobaoApi
};

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cookieParser());

/**
 * 测试
 */
app.use('/test', function (req, res, next) {
    console.log('req.query', req.query);
    console.log('req.body', req.body);

    return res.json({
        query: req.query,
        body: req.body
    });
});

/**
 * Admin Apis
 */
app.use('/api/data', require('./api/data')(storage, config));

/**
 * 启动服务器
 */
let server = app.listen(config.port_data, function () {
    console.log('Express server listening on port ' + server.address().port);

    storage.schedule = require('./spider/schedule')(storage, config);
    storage.tasks = require('./tasks')(storage, config);
});